package com.wcards.config;

import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

//JWT令牌配置类
public class JWT {
    //设置秘钥
    public static final String TOKEN_KEY = "yigedaheiwar";

    //生成token方法
    public static String Tokenget(Map<String, Object> claims) {
        //添加负载
        String token = com.auth0.jwt.JWT.create()
                .withClaim("claims", claims)//添加负载
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24))//添加过期时间
                .sign(Algorithm.HMAC256(TOKEN_KEY));//添加密钥
        return token;
    }

    //单纯验证token是否正确的方法
    public static boolean checktoken(String token) {
        try {
            JWTVerifier jwtVerifier = com.auth0.jwt.JWT.require(Algorithm.HMAC256(TOKEN_KEY)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);//验证token，生成解析后的JWT对象
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //验证token方法,并且返回数据
    public static Map<String, Object> returnToken(String token) {
        JWTVerifier jwtVerifier = com.auth0.jwt.JWT.require(Algorithm.HMAC256(TOKEN_KEY)).build();//生成验证器，对秘钥进行加密处理
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT.getClaim("claims").asMap();
    }
}

